package com.lenovo.vod.player.setting;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

//import com.lenovo.dll.nebula.vod.bookmark.util.BookMarkConstant;
//import com.lenovo.dll.nebula.vod.bookmark.util.BookMarkWorkTool;
//import com.lenovo.dll.nebula.vod.player.setting.SettingBaseFragment;
//import com.lenovo.dll.nebula.vod.player.setting.util.LeDialog;
//import com.lenovo.dll.nebula.vod.player.setting.util.LeLoading;
import com.lenovo.vod.player.Constant;
import com.lenovo.vod.player.MainActivity;
import com.lenovo.vod.player.R;
import com.lenovo.vod.player.setting.util.LeEditText;
import com.lenovo.vod.player.setting.util.LeEditText.TextListener;
import com.lenovo.vod.player.setting.util.MediaBaseArrayAdapter;
import com.lenovo.vod.player.setting.util.MediaDisplayArrayAdapter;
import com.lenovo.vod.player.setting.util.MediaOptionArrayAdapter;
import com.lenovo.vod.player.setting.util.NumberUtils;
import com.lenovo.vod.player.setting.util.StringUtils;

public class SettingFragment extends SettingBaseFragment {

    private int mOptionLever = -1, mOptionFirst = -1, mOptionSecond = -1;
    private Editor mEditor;
    private SharedPreferences mSharedPreferences;
    private Handler mMainHandler;
    // from other activity
    private int mTotalVideoNum;
    private boolean mIsMovie;

    private boolean mIsCollected = false;
    private boolean mIsResult = false;
    private LeEditText mLeEditText;
    private MediaOptionArrayAdapter mMediaOptionArrayAdapter;
    private String mMediaQualityValue;
    private String mMediaVoiceValue;
    private String mMediaBreakpointValue;
    private MediaDisplayArrayAdapter mMediaDisplayArrayAdapter;
    private List<String> mDifferents;
    private List<String> mTransferArgument;
    private View mView;
    private Resources mResources;
    private String mSelfAda;
    private String mMediaId;
    private String mPosterUrl;
    private String mMediaName;
    private String mVideoCode;
    private String mRelateType;
    private int mVideoType;
//    private LeDialog mLeDialog;
    private String mCancleCol;
    private String mCol;
//    private LeLoading mLeLoading;
    private String [] mDefintions = {"definitionStandard" , "definitionHigh" ,
                "definitionSuper" ,"definitionAdaption"};
    private String [] mSounds = {"soundStandard" , "soundHuman" , "soundCinema"};
    private String [] mSwitchs = {"switchOpen", "switchClose"};
   

//    private Handler mVSFragmentHandler = new Handler() {
//
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//            case BookMarkConstant.BOOKMARK_FAVORITE_DISMISS_DIALOG:
//                if (mLeDialog.isShowing()) {
//                    mLeDialog.dismiss();
//                }
//                if (mLeLoading.isShowing()) {
//                    mLeLoading.dismiss();
//                }
//                mIsResult = false;
//                break;
//            case BookMarkConstant.BOOKMARK_FAVORITE_SUCCESS:
//                mIsResult = true;
//                if (mIsCollected) {
//                    mLeDialog
//                            .buildDialog(R.string.vodplayer_setting_collectCancel);
//                } else {
//                    mLeDialog
//                            .buildDialog(R.string.vodplayer_setting_collectSuccess);
//                }
//                sendEmptyMessageDelayed(
//                        BookMarkConstant.BOOKMARK_FAVORITE_DISMISS_DIALOG, 2000);
//                break;
//            case BookMarkConstant.BOOKMARK_FAVORITE_CONNECTFAIL:
//            case BookMarkConstant.BOOKMARK_FAVORITE_XMLERROR:
//            case BookMarkConstant.BOOKMARK_FAVORITE_COMMITFAIL:
//                mLeDialog
//                        .buildDialog(R.string.vodplayer_setting_collectConnectionError);
//                mIsResult = true;
//                sendEmptyMessageDelayed(
//                        BookMarkConstant.BOOKMARK_FAVORITE_DISMISS_DIALOG, 2000);
//                break;
//            case BookMarkConstant.BOOKMARK_FAVORITE_TIMEOUT:
//                if (!mIsResult) {
//                    mLeLoading.build(R.string.vodplayer_setting_collectLoading);
//                    sendEmptyMessageDelayed(
//                            BookMarkConstant.BOOKMARK_FAVORITE_DISMISS_DIALOG,
//                            2000);
//                }
//                break;
//            case BookMarkConstant.BOOKMARK_FAVORITE_COLLECTION_FALSE:
//                mIsCollected = false;
//                mMediaOptionArrayAdapter.setCollection(mIsCollected, mCol,
//                        mCancleCol);
//                break;
//            case BookMarkConstant.BOOKMARK_FAVORITE_COLLECTION_TRUE:
//                mIsCollected = true;
//                mMediaOptionArrayAdapter.setCollection(mIsCollected, mCol,
//                        mCancleCol);
//                break;
//            }
//            super.handleMessage(msg);
//        }
//
//    };

    /**
     * Fragment Create View
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mView = inflater.inflate(
                R.layout.vodplayer_setting_mediaoption_fragment, container,
                false);
        return mView;
    }

    /**
     * Activity Create
     */
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        findViewWithFragment();
        getParas();

        mSharedPreferences = this.getActivity().getSharedPreferences(
                "mediaOption", Context.MODE_PRIVATE | Context.MODE_APPEND);
        mEditor = mSharedPreferences.edit();
//        initDialog();
        sendConfigMessage();
    }

    /**
     * destory
     */
    public void destroy() {
//        mVSFragmentHandler
//                .removeMessages(Constant.MSG_DISMISS_COLLECTION_VIDEO);
//        mVSFragmentHandler.removeMessages(Constant.MSG_COLLECTION_INTERNET);

        if (mLeEditText != null) {
            mLeEditText.init();
        }
        mOptionFirst = -1;
        mOptionLever = -1;
        mOptionSecond = -1;

        mIsResult = false;

        mMediaQualityValue = null;
        mMediaVoiceValue = null;
        mMediaBreakpointValue = null;

    }

    /**
     * Change the title of the menu at all levels of information
     * 
     * @param index
     *            menu ID
     * @param lever
     *            lever index
     */
    private void bindListViewInfoByArrays(int textArrayResId,
            String textArrayValue,String [] currents) {
        mLvOptions.setAdapter(MediaBaseArrayAdapter.createFromResource(
                this.getActivity(), textArrayResId, textArrayValue,currents));
    }

    /**
     * Binding show choice
     * 
     */
    private void bindListViewSelect() {
        ArrayList<String> items = new ArrayList<String>();
        String cnNum = mResources
                .getString(R.string.vodplayer_setting_number_cnNum);
        String cnW = mResources
                .getString(R.string.vodplayer_setting_number_cnW);
        String mL = mResources.getString(R.string.vodplayer_setting_number_mL);
        String mW = mResources.getString(R.string.vodplayer_setting_number_mW);
        String mY = mResources.getString(R.string.vodplayer_setting_number_mY);
        String mDi = mResources.getString(R.string.vodplayer_setting_select_di);
        String mJi = mResources.getString(R.string.vodplayer_setting_select_ji);
        for (int i = 1; i < mTotalVideoNum + 1; i++) {
            String cnNumStr = NumberUtils.intToCnNum(i, cnNum, cnW,
                    mW.charAt(0), mY.charAt(0), mL.charAt(0));
            items.add(mDi + cnNumStr + mJi);
        }
        mLvOptions.setAdapter(new ArrayAdapter<String>(this.getActivity(),
                R.layout.vodplayer_setting_option_listitems,
                R.id.vodplayer_setting_tvOption, items));
    }

    /**
     * visible ListView's content
     * @param position
     */
    private void visibleListViewOptionContent() {
        if (mIsMovie) {
            bindListViewOptionByArrays(R.array.vodplayer_setting_level1_movie);
        } else {
            bindListViewOptionByArrays(R.array.vodplayer_setting_level1_tv);
        }
       // synchroNetData();
        setListViewOptions();
    }

    /**
     * sync Net Data
     */
    private void synchroNetData() {
        HashMap<String, Object> hm = new HashMap<String, Object>();
        hm.put("MediaID", mMediaId);
//        BookMarkWorkTool mBookMarkWorkTool = new BookMarkWorkTool();
//        mBookMarkWorkTool.searchFavorite(hm, mVSFragmentHandler);
    }

    /**
     * Binding ListView's Option Menu Content
     */
    @Override
    public void bindListViewOptionByArrays(int textArrayResId) {
        mCancleCol = mResources
                .getString(R.string.vodplayer_setting_option_canclecollection);
        mCol = mResources
                .getString(R.string.vodplayer_setting_option_collection);
        mMediaOptionArrayAdapter.changeData(textArrayResId, mCancleCol, mCol);
        mLvOptions.setAdapter(mMediaOptionArrayAdapter);
        mOptionLever = 1;
    }

    private void sendConfigMessage() {
        mMediaQualityValue = mSharedPreferences.getString("mMediaDisplays",
                Constant.PARA_DEFINITION_ADAPTION);
        mMediaVoiceValue = mSharedPreferences.getString("mMediaVoices",
                Constant.PARA_SOUND_STANDARD);
        mMediaBreakpointValue = mSharedPreferences.getString(
                "mMediaBreakpoints", Constant.PARA_SWITCH_OPEN);

        Message mediaQualityMsg = new Message();
        mediaQualityMsg.what = Constant.MSG_PICTURE_QUALITY;
        mediaQualityMsg.obj = mMediaQualityValue;
        mMainHandler.sendMessage(mediaQualityMsg);

        Message mMediaVoiceMsg = new Message();
        mMediaVoiceMsg.what = Constant.MSG_SOUND_EFFECT;
        mMediaVoiceMsg.obj = mMediaVoiceValue;
        mMainHandler.sendMessage(mMediaVoiceMsg);

        Message mMediaBreakpointMsg = new Message();
        mMediaBreakpointMsg.what = Constant.MSG_BREAKPOINT_PLAY;
        mMediaBreakpointMsg.obj = mMediaBreakpointValue;
        mMainHandler.sendMessage(mMediaBreakpointMsg);

    }

    private void bindListViewDisplay() {
        mMediaQualityValue = mSharedPreferences.getString("mMediaDisplays",
                Constant.PARA_DEFINITION_ADAPTION);
        mSelfAda = "definitionAdaption";
        mLvOptions.setAdapter(MediaDisplayArrayAdapter.createFromResource(
                this.getActivity(), R.array.vodplayer_setting_level2_quality,
                mMediaQualityValue, mDifferents, mTransferArgument, mSelfAda,mDefintions));

    }

    /**
     * set Movie's all quality
     * @param definitions
     */
    public void setMovieDefinition(String[] definitions) {
        if (definitions == null || definitions.length == 0) {
            return;
        }
        mMediaQualityValue = mSharedPreferences.getString("mMediaDisplays",
                Constant.PARA_DEFINITION_ADAPTION);
        mTransferArgument = StringUtils.getStringArrayByResourceId(definitions);
        mDifferents = StringUtils.findDifferentWithArray(mDefintions, definitions);
        mMediaDisplayArrayAdapter.differentDatas(mDifferents,
                mMediaQualityValue, mTransferArgument,mDefintions);

    }

    private void setListViewOptions() {
        mLvOptions.setVisibility(View.VISIBLE);
        mLvOptions.requestFocus();
    }

//    private void initDialog() {
//        mLeDialog = new LeDialog(this.getActivity(),
//                R.style.vodcategory_LeDialog);
//        mLeDialog.setOwnerActivity(this.getActivity());
//        mLeDialog.initDialog();
//
//        mLeLoading = new LeLoading(this.getActivity(),
//                R.style.vodcategory_LeLoading);
//        mLeLoading.setOwnerActivity(this.getActivity());
//        mLeLoading.init();
//    }

    /**
     * show ListView
     */
    public void show() {
        visibleListViewOptionContent();
    }

    /**
     * hide ListView
     */
    public void hideListViewOptions() {
        if (mLvOptions.getVisibility() == View.VISIBLE) {
            if (mIvDownIco.getVisibility() == View.VISIBLE) {
                mIvDownIco.setVisibility(View.GONE);
            }
            if (mIvUpIco.getVisibility() == View.VISIBLE) {
                mIvUpIco.setVisibility(View.GONE);
            }
            if (mTvHead.getVisibility() == View.VISIBLE) {
                mTvHead.setVisibility(View.GONE);
            }
            mLvOptions.setSelected(false);
            mLvOptions.setVisibility(View.GONE);
            mOptionSecond = -1;
        }
    }

    /**
     * Get Intent parameters
     */
    public void getParas() {
        Bundle mExtras = getActivity().getIntent().getExtras();
        mTotalVideoNum = mExtras.getBundle("EpisodeDetail").size();
        mMediaId = mExtras.getString("Code");
        mPosterUrl = mExtras.getString("PosterUrl");
        mMediaName = mExtras.getString("Name");
        mVideoCode = mExtras.getBundle("EpisodeDetail").getString("VideoCode");
        mRelateType = mExtras.getBundle("Relate").getString("Type");
        mVideoType = mExtras.getInt("Type");
        if (mVideoType == 0)
            mIsMovie = true;
        else
            mIsMovie = false;
    }

    private void collectVideo() {
        HashMap<String, Object> hm = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hhmm");
        Date mDate = new Date(System.currentTimeMillis());
        String currentTime = sdf.format(mDate);
        hm.put("createTime", currentTime);
        hm.put("mediaType", mVideoType + "");
        hm.put("smallImage1", mPosterUrl);
        hm.put("MediaID", mMediaId);
        hm.put("favoriteName", mMediaName);
        hm.put("categoryName", mRelateType);
        hm.put("videoCode", mVideoCode);
//        BookMarkWorkTool mBookMarkWorkTool = new BookMarkWorkTool();
//        mBookMarkWorkTool.addFavorite(hm, mVSFragmentHandler);
        hideListViewOptions();
    }

    private void cancleCollectVideo() {
        HashMap<String, Object> hm = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hhmm");
        Date mDate = new Date(System.currentTimeMillis());
        String currentTime = sdf.format(mDate);
        hm.put("createTime", currentTime);
        hm.put("mediaType", mVideoType + "");
        hm.put("smallImage1", mPosterUrl);
        hm.put("MediaID", mMediaId);
        hm.put("favoriteName", mMediaName);
        hm.put("categoryName", mRelateType);
        hm.put("videoCode", mVideoCode);
        hm.put("selectIndex", 0);
//        BookMarkWorkTool mBookMarkWorkTool = new BookMarkWorkTool();
//        mBookMarkWorkTool.delFavorite(hm, mVSFragmentHandler);
        hideListViewOptions();

    }

    private void findViewWithFragment() {
        mMediaOptionArrayAdapter = new MediaOptionArrayAdapter(
                this.getActivity());
        mMediaDisplayArrayAdapter = new MediaDisplayArrayAdapter(
                this.getActivity());
        MainActivity mainActivity = (MainActivity) this.getActivity();
        mMainHandler = mainActivity.getEngine().getSettingHandler();
        mResources = this.getResources();
    }

    /**
     * ListView option click event
     * 
     * @param index
     *            option index
     */
    public void optionListViewItemClick(int index) {
        mTvHead.setVisibility(View.GONE);
        mIvDownIco.setVisibility(View.GONE);
        mIvUpIco.setVisibility(View.GONE);
        Message msg = new Message();
        mOptionFirst = index;
        if (mIsMovie) {
            mOptionFirst += 1;
        }
        switch (mOptionLever) {
        case 1:
            switch (mOptionFirst) {
            case 0:
                bindListViewSelect();
                setListViewOptions();
                break;
            case 1:
                bindListViewDisplay();
                setHeadTextData(mOptionFirst, mOptionLever,
                        R.array.vodplayer_setting_level1_tv);
                setListViewOptions();
                break;
            case 2:
                mMediaVoiceValue = mSharedPreferences.getString("mMediaVoices",
                        Constant.PARA_SOUND_STANDARD);
                bindListViewInfoByArrays(
                        R.array.vodplayer_setting_level2_voice,
                        mMediaVoiceValue,mSounds);
                setHeadTextData(mOptionFirst, mOptionLever,
                        R.array.vodplayer_setting_level1_tv);
                setListViewOptions();
                break;
            case 3:
//                if (mIsCollected) {
//                    cancleCollectVideo();
//                } else {
//                    collectVideo();
//                }
                break;
            case 4:

                mMainHandler.sendEmptyMessage(Constant.MSG_RELEVANCE);
                hideListViewOptions();
                break;
            case 5:
                setHeadTextData(mOptionFirst, mOptionLever,
                        R.array.vodplayer_setting_level1_tv);
                mLvOptions.setVisibility(View.GONE);
                setLeEditText();
                break;
            case 6:
                mMediaBreakpointValue = mSharedPreferences.getString(
                        "mMediaBreakpoints", Constant.PARA_SWITCH_OPEN);
                bindListViewInfoByArrays(
                        R.array.vodplayer_setting_level2_breakpoint,
                        mMediaBreakpointValue,mSwitchs);
                setHeadTextData(mOptionFirst, mOptionLever,
                        R.array.vodplayer_setting_level1_tv);
                setListViewOptions();
                break;
            }
            mOptionSecond = mOptionFirst;
            mOptionLever = 2;
            break;
        case 2:
            switch (mOptionSecond) {
            case 0:
                msg.what = Constant.MSG_TELEPLAY_NUM;
                msg.obj = index + 1;
                mMainHandler.sendMessage(msg);
                hideListViewOptions();
                break;
            case 1:
                String currentQuality = mDefintions[index];
                if (mTransferArgument == null || mTransferArgument.size() == 0
                        || mTransferArgument.isEmpty()) {
                    setHeadTextData(1, mOptionLever,
                            R.array.vodplayer_setting_level1_tv);
                    if (!mSelfAda.equals(currentQuality)) {
                        return;
                    }
                } else {
                    if (mDifferents != null && !mDifferents.isEmpty()
                            && mDifferents.contains(currentQuality)) {
                        setHeadTextData(1, mOptionLever,
                                R.array.vodplayer_setting_level1_tv);
                        if (!mSelfAda.equals(currentQuality)) {
                            return;
                        }
                    }
                }
                msg.what = Constant.MSG_PICTURE_QUALITY;
                msg.obj = mDefintions[index];
//                msg.obj = mediaQualitys.get(index);
                mEditor.putString("mMediaDisplays", mDefintions[index]);
//                mEditor.putString("mMediaDisplays", mediaQualitys.get(index));
                mEditor.commit();
                mMainHandler.sendMessage(msg);
                break;
            case 2:
//                List<String> mMediaVoices = StringUtils
//                        .getStringArrayByResourceId(this.getResources(),
//                                R.array.vodplayer_setting_level2_voice);
                msg.what = Constant.MSG_SOUND_EFFECT;
//                msg.obj = mMediaVoices.get(index);
                msg.obj = mSounds[index];
//                mEditor.putString("mMediaVoices", mMediaVoices.get(index));
                mEditor.putString("mMediaVoices", mSounds[index]);
                mEditor.commit();
                mMainHandler.sendMessage(msg);
                break;
            case 3:
                break;
            case 4:
                break;
            case 5:
                break;
            case 6:
//                List<String> mMediaBreakpoints = StringUtils
//                        .getStringArrayByResourceId(this.getResources(),
//                                R.array.vodplayer_setting_level2_breakpoint);
                msg.what = Constant.MSG_BREAKPOINT_PLAY;
//                msg.obj = mMediaBreakpoints.get(index);
                msg.obj = mSwitchs[index];
//                mEditor.putString("mMediaBreakpoints",
//                        mMediaBreakpoints.get(index));
                mEditor.putString("mMediaBreakpoints",
                        mSwitchs[index]);
                mEditor.commit();
                mMainHandler.sendMessage(msg);
                break;
            }
            hideListViewOptions();
            break;
        }
    }

    private void setLeEditText() 
    {
        mLeEditText = (LeEditText) this.getActivity().findViewById(
                R.id.vodplayer_setting_leSkipTime);
        mLeEditText.setVisibility(View.VISIBLE);
        mLeEditText.requestFocus();

        mLeEditText.setTextListener(new TextListener() 
        {
            /**
             * NewEdit enter event
             */
            public void onEnterDown(String value) {
                if (mLeEditText.getVisibility() == View.VISIBLE) {
                    Message msg = new Message();
                    msg.what = Constant.MSG_SEEK_TIME;
                    msg.obj = value;
                    mMainHandler.sendMessage(msg);
                    mLeEditText.init();
                    mTvHead.setVisibility(View.GONE);
                    mLeEditText.setVisibility(View.GONE);
                }

            }

            /**
             * NewEdit back event
             */
            public void onBackDown(String value) {
                if (mLeEditText.getVisibility() == View.VISIBLE) {
                    mLeEditText.init();
                    destroy();
                    mTvHead.setVisibility(View.GONE);
                    mLeEditText.setVisibility(View.GONE);
                }

            }
        });
    }

    /**
     * destory
     */
    public void onDestroy() {
        destroy();
        super.onDestroy();
    }

}
